package net.njcp.icodes.builder;

import net.njcp.icodes.bo.Configuration;
import net.njcp.icodes.bo.ParserModul;
import net.njcp.icodes.parsing.XNode;
import net.njcp.icodes.parsing.XPathParser;

import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName XmlParserBuilder
 * @Description: TODO
 * @Author 柳拓
 * @Date 2019/8/16
 * @Version V1.0
 **/
public class XmlParserBuilder {

    private final XPathParser parser;
    private Configuration configuration;

    public XmlParserBuilder(Reader reader, Configuration configuration) {
        this(new XPathParser(reader, false, null, null));
        this.configuration = configuration;
    }

    private XmlParserBuilder(XPathParser parser){
        this.parser = parser;
    }

    public Configuration parse() {
        parseParserXml(parser.evalNode("/parser"));
        return configuration;
    }

    public void parseParserXml(XNode node){
        String namespace = node.getStringAttribute("namespace");
        List<ParserModul> parserModuls = parseAttributes(parser.evalNode("/parser/attributes"));
        configuration.registerParser(namespace, parserModuls);
    }

    public List<ParserModul> parseAttributes(XNode node){
        List<ParserModul> parserModuls = new ArrayList<>();
        List<XNode> childNodes = node.getChildren();
        for (XNode childNode:childNodes) {
            ParserModul parserModul = new ParserModul();
            parserModul.setId(childNode.getStringAttribute("id"));
            String type = childNode.getStringAttribute("type");
            parserModul.setType(type);
            //如果是java包装类型
            if(type.indexOf("java.lang") > -1){
                parserModul.setStartBit(Short.parseShort(childNode.getStringAttribute("startBit")));
                parserModul.setSumBit(Short.parseShort(childNode.getStringAttribute("sumBit")));
                parserModul.setEndType(Short.parseShort(childNode.getStringAttribute("endType")));
                parserModul.setOffset(Integer.parseInt(childNode.getStringAttribute("offset")));
                parserModul.setAccuracy(Double.parseDouble(childNode.getStringAttribute("accuracy")));
                parserModul.setStringType(childNode.getStringAttribute("stringType"));
            }else if(type.indexOf("List") >-1) {
                parserModul.setIInitListSize(childNode.getStringAttribute("init"));
                parserModul.setISelectorDataParser(childNode.getStringAttribute("switch"));
            }else {
                parserModul.setISelectorDataParser(childNode.getStringAttribute("switch"));
            }
            parserModuls.add(parserModul);
        }
        return parserModuls;
    }

}
